<template>
  <view class="my-info-container">
    <!-- 表单内容区域 -->
    <view class="form-container">
      <u--form
          :model="formData"
          ref="form"
          :rules="rules"
          labelPosition="left"
          labelWidth="120"
      >
        <!-- 头像 -->
        <u-form-item label="头像" prop="head" borderBottom class='formItemWp'>
          <view style="display: flex;align-items:center;">
            <view style="flex: 1;color: #c0c4cc;">
              点击图标选择头像
            </view>
            <view class="avatarImgWp">
              <button class="u-reset-button" open-type="chooseAvatar"
                      @chooseavatar="onChooseAvatar">
                <img v-if="formData.head!=''" :src="formData.head" alt="" class='avatarImg'>
                <img v-if="formData.head==''"
                     src="https://file.casugn.com/storecompcard/temp/456_1757666005254.png"
                     alt="默认头像" class='defaultAvatarImg'>
              </button>

            </view>
            <view class="">
              <u-icon name="arrow-right" color="#c9cdd4" size="32"></u-icon>
            </view>
          </view>
        </u-form-item>

        <!-- 姓名 -->
        <u-form-item label="昵称" prop="name" borderBottom>
          <u--input
              v-model="formData.name"
              placeholder="请输入昵称"
              border="none"
              clearable
          ></u--input>
        </u-form-item>

        <!-- 性别 -->
        <u-form-item label="性别" prop="sex" borderBottom>
          <u-radio-group v-model="formData.sex" size="28">
            <u-radio :name="1" label="男" activeColor="#5ba0f2" icon-size="28"
                     label-size="28"></u-radio>
            <u-radio :name="2" label="女" activeColor="#5ba0f2" icon-size="28"
                     label-size="28"></u-radio>
          </u-radio-group>
        </u-form-item>

        <!-- 手机号 -->
        <u-form-item label="手机号" prop="mobile" borderBottom>
          <u--input
            v-model="formData.mobile"
            placeholder="请输入手机号"
            border="none"
            clearable
            type="number"
            maxlength="11"
          ></u--input>
        </u-form-item>

        <!-- 备注 -->
        <u-form-item label="简介" prop="remark" borderBottom>
          <u--textarea
              v-model="formData.remark"
              placeholder="请输入简介信息"
              border="none"
              maxlength="200"
              count
          ></u--textarea>
        </u-form-item>
      </u--form>
    </view>

    <!-- 底部提交按钮 -->
    <view class="bottom-action">
      <u-button
          :loading="loading"
          :disabled="loading"
          @click="submitForm"
          type="primary"
          size="large"
          customStyle="background: linear-gradient(135deg, #4a90e2 0%, #5ba0f2 100%); border: none; border-radius: 44rpx;"
      >
        {{ loading ? '保存中...' : '保存' }}
      </u-button>
    </view>
  </view>
</template>

<script>
import {mapGetters} from 'vuex'
import baseConfig from '@/config/baseUrl.js'

export default {
  name: 'MyInfo',

  data() {
    return {
      statusBarHeight: 0,
      loading: false,
      defaultAvatar: 'https://file.casugn.com/storecompcard/temp/默认头像_1705454811406.png',

      formData: {
        id: '',
        head: '',
        name: '',
        mobile: '',
        sex: null,
        remark: '',
        version: 1,
        style: "1",
        unionId: ''
      },

      rules: {
        name: [
          {
            required: true,
            message: '请输入姓名',
            trigger: ['blur', 'change']
          },
          {
            min: 2,
            max: 20,
            message: '姓名长度在2到20个字符',
            trigger: ['blur', 'change']
          }
        ],
        mobile: [
          {
            pattern: /^1[3-9]\d{9}$/,
            message: '请输入正确的手机号码',
            trigger: ['blur', 'change']
          }
        ]
      }
    }
  },

  computed: {
    ...mapGetters(['openId'])
  },

  onLoad() {
    this.getSystemInfo()
    this.getUserInfo()
  },

  methods: {
    // 换头像
    async onChooseAvatar(e) {
      const {
        avatarUrl
      } = e.detail
      //上传图片地址
      let imgUrl = await this.uploadFilePromise(avatarUrl)
      console.log(imgUrl, 'imgUrl');
      this.formData.head = imgUrl
    },
    uploadFilePromise(url) {
      return new Promise((resolve, reject) => {
        let a = uni.uploadFile({
          url: baseConfig.uploadUrl + '/sys/common/upload',
          filePath: url,
          name: 'file',
          success: (res) => {
            let data = JSON.parse(res.data)
            if (data.success) {
              resolve(data.message)
            }
          }
        });
      })
    },
    // 获取系统信息
    getSystemInfo() {
      const systemInfo = uni.getSystemInfoSync()
      this.statusBarHeight = systemInfo.statusBarHeight || 0
    },

    // 返回上一页
    goBack() {
      uni.navigateBack()
    },

    // 获取用户信息
    async getUserInfo() {
      if (!this.openId) {
        uni.showToast({
          title: '用户信息获取失败',
          icon: 'none'
        })
        return
      }

      uni.showLoading({
        title: '加载中...'
      })

      try {
        const res = await this.$api.queryCurrentCardByOpenId({
          openId: this.openId
        })

        if (res.success && res.result) {
          const userInfo = res.result
          this.formData = {
            id: userInfo.id || '',
            head: userInfo.head || '',
            name: userInfo.name || '',
            mobile: userInfo.mobile || '',
            sex: userInfo.sex || null,
            remark: userInfo.remark || '',
            version: userInfo.version || 1,
            style: "1",
            unionId: userInfo.unionId || ''
          }

          console.log('用户信息回显成功:', this.formData)
        } else {
          uni.showToast({
            title: res.message || '获取用户信息失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('获取用户信息失败:', error)
        uni.showToast({
          title: '获取用户信息失败',
          icon: 'none'
        })
      } finally {
        uni.hideLoading()
      }
    },

    // 选择头像
    chooseAvatar() {
      uni.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          const tempFilePath = res.tempFilePaths[0]
          this.uploadAvatar(tempFilePath)
        },
        fail: (error) => {
          console.error('选择头像失败:', error)
          uni.showToast({
            title: '选择头像失败',
            icon: 'none'
          })
        }
      })
    },

    // 上传头像
    uploadAvatar(filePath) {
      uni.showLoading({
        title: '上传中...'
      })

      // 这里需要根据你的实际上传接口进行调整
      uni.uploadFile({
        url: 'your-upload-url', // 替换为实际的上传接口
        filePath: filePath,
        name: 'file',
        header: {
          // 添加必要的请求头
        },
        success: (uploadRes) => {
          try {
            const data = JSON.parse(uploadRes.data)
            if (data.success) {
              this.formData.head = data.result.url // 根据实际返回结构调整
              uni.showToast({
                title: '头像上传成功',
                icon: 'success'
              })
            } else {
              uni.showToast({
                title: data.message || '上传失败',
                icon: 'none'
              })
            }
          } catch (error) {
            console.error('解析上传结果失败:', error)
            uni.showToast({
              title: '上传失败',
              icon: 'none'
            })
          }
        },
        fail: (error) => {
          console.error('上传失败:', error)
          uni.showToast({
            title: '上传失败',
            icon: 'none'
          })
        },
        complete: () => {
          uni.hideLoading()
        }
      })
    },

    // 提交表单
    async submitForm() {
      // 表单验证
      try {
        await this.$refs.form.validate()
      } catch (error) {
        console.log('表单验证失败:', error)
        return
      }

      if (!this.openId) {
        uni.showToast({
          title: '用户信息获取失败',
          icon: 'none'
        })
        return
      }

      this.loading = true

      try {
        // 准备提交数据
        const submitData = {
          ...this.formData,
          openId: this.openId
        }

        console.log('提交数据:', submitData)

        const res = await this.$api.updateUserInfo(submitData)

        if (res.success) {
          uni.showToast({
            title: '保存成功',
            icon: 'none'
          })

          // 更新本地用户信息
          // this.$store.commit('userInfo', res.result)

          // 延迟返回上一页
          setTimeout(() => {
            this.goBack()
          }, 1500)
        } else {
          uni.showToast({
            title: res.message || '保存失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('保存用户信息失败:', error)
        uni.showToast({
          title: '保存失败',
          icon: 'none'
        })
      } finally {
        this.loading = false
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.my-info-container {
  min-height: 100vh;
  background-color: #f5f7fa;
  display: flex;
  flex-direction: column;
}

.formItemWp {
  margin: 0 50upx;
  height: 108rpx;
  border-bottom: #666;
}

.avatarImgWp {
  margin-right: 16rpx;

  .defaultAvatarImg {
    background-color: #c9cdd4;
    border-radius: 4rpx;
    width: 80rpx;
    height: 80rpx;
  }

  .avatarImg {
    border-radius: 4rpx;
    width: 80rpx;
    height: 80rpx;
  }

}

.defaultAvatarImg {
  background-color: #c9cdd4;
  border-radius: 4rpx;
  width: 80rpx;
  height: 80rpx;
}

.status-bar {
  background-color: #fff;
}

.custom-navbar {
  background-color: #fff;
  border-bottom: 2rpx solid #ebeef5;
  position: sticky;
  top: 0;
  z-index: 1000;
}

.navbar-content {
  height: 88rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 30rpx;
}

.navbar-left {
  width: 80rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.navbar-title {
  flex: 1;
  text-align: center;
  font-size: 36rpx;
  font-weight: 600;
  color: #303133;
}

.navbar-right {
  width: 80rpx;
}

.form-container {
  flex: 1;
  background-color: #fff;
  margin: 20rpx;
  border-radius: 20rpx;
  overflow: hidden;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
}

.avatar-container {
  position: relative;
  width: 120rpx;
  height: 120rpx;
  border-radius: 60rpx;
  overflow: hidden;
  background-color: #f5f5f5;
}

.avatar {
  width: 100%;
  height: 100%;
}

.avatar-mask {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.3);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.avatar-container:active .avatar-mask {
  opacity: 1;
}

.bottom-action {
  padding: 30rpx;
  background-color: #fff;
  border-top: 2rpx solid #ebeef5;
}

// uView 表单项样式调整
::v-deep .u-form-item {
  padding: 30rpx 24rpx;

  .u-form-item__label {
    font-size: 28rpx;
    font-weight: 500;
    color: #303133;
  }

  .u-form-item__body {
    flex: 1;
    min-width: 0;
  }
}

::v-deep .u-radio-group {
  .u-radio {
    margin-right: 60rpx;

    &:last-child {
      margin-right: 0;
    }

    .u-radio__icon-wrap {
      width: 36rpx !important;
      height: 36rpx !important;
    }

    .u-radio__label {
      font-size: 30rpx !important;
      color: #303133 !important;
      margin-left: 16rpx !important;
    }
  }
}

::v-deep .u-input {
  font-size: 28rpx;
  color: #303133;

  .u-input__content {
    .u-input__content__field-wrapper {
      .u-input__content__field-wrapper__field {
        text-align: right;
      }
    }
  }
}

::v-deep .u-textarea {
  .u-textarea__textarea {
    font-size: 28rpx;
    color: #303133;
  }
}
</style>
